// 路由守卫 - 页面级认证控制
import { isWhitelisted } from '@/config/auth-whitelist.js'

// 存储当前页面路径
let currentPath = ''

// 初始化路由守卫
export const initRouterGuard = () => {
  // 监听页面跳转
  const originalNavigateTo = uni.navigateTo
  const originalRedirectTo = uni.redirectTo
  const originalSwitchTab = uni.switchTab
  const originalReLaunch = uni.reLaunch
  const originalNavigateBack = uni.navigateBack

  // 重写导航方法
  uni.navigateTo = function(options) {
    checkAuthBeforeNavigate(options.url)
    return originalNavigateTo.call(this, options)
  }

  uni.redirectTo = function(options) {
    checkAuthBeforeNavigate(options.url)
    return originalRedirectTo.call(this, options)
  }

  uni.switchTab = function(options) {
    checkAuthBeforeNavigate(options.url)
    return originalSwitchTab.call(this, options)
  }

  uni.reLaunch = function(options) {
    checkAuthBeforeNavigate(options.url)
    return originalReLaunch.call(this, options)
  }

  // 更新当前路径
  uni.navigateBack = function(options) {
    // 导航返回时也需要更新路径
    setTimeout(() => {
      updateCurrentPath()
    }, 100)
    return originalNavigateBack.call(this, options)
  }

  // 初始路径更新
  updateCurrentPath()
}

// 检查导航前的认证
const checkAuthBeforeNavigate = (url) => {
  const path = extractPathFromUrl(url)
  currentPath = path
  
  if (!isWhitelisted(path)) {
    console.log('目标页面需要认证:', path)
    // 这里可以触发认证检查
    // 在实际项目中，可能需要等待认证完成后再跳转
  } else {
    console.log('目标页面在白名单中:', path)
  }
}

// 更新当前路径
const updateCurrentPath = () => {
  const pages = getCurrentPages()
  if (pages.length > 0) {
    const currentPage = pages[pages.length - 1]
    currentPath = currentPage.route ? `/${currentPage.route}` : window.location.pathname
    console.log('当前路径更新为:', currentPath)
  }
}

// 从URL中提取路径
const extractPathFromUrl = (url) => {
  if (!url) return ''
  
  // 移除查询参数
  const path = url.split('?')[0]
  // 确保以/pages/开头
  return path.startsWith('/') ? path : `/${path}`
}

// 获取当前路径
export const getCurrentPath = () => currentPath

// 检查当前页面是否需要认证
export const requiresAuthentication = () => {
  return !isWhitelisted(currentPath)
}